/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package viewcontrollers;


import pojos.Reports;
import viewcontrollers.util.JsfUtil;
import viewcontrollers.util.PaginationHelper;
import beans.ReportsFacade;

import java.util.Date;
import java.util.List;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import pojos.Employees;
import pojos.Projects;
import pojos.TimeLog;
/**
 *
 * @author A7med Kotb
 */
@ManagedBean(name = "reportsController")
@SessionScoped
public class ReportsController {

    private Employees employee;
    private Projects project;
    private Date startDate;
    private Date endDate;
    private Reports current;
    private DataModel items = null;
    private DataModel searchItems = null;
    @EJB
    private beans.ReportsFacade ejbFacade;
    private PaginationHelper pagination;
    private PaginationHelper searchPagination;
    private int selectedItemIndex;
    private String timeLogId;

    public Reports getCurrent() {
        return current;
    }

    public void setCurrent(Reports current) {
        this.current = current;
    }
    
    public String getTimeLogId() {
        return timeLogId;
    }

    public void setTimeLogId(String timeLogId) {
        this.timeLogId = timeLogId;
    }

    public Projects getProject() {
        return project;
    }

    public void setProject(Projects project) {
        this.project = project;
    }

    public Employees getEmployee() {
        return employee;
    }

    public void setEmployee(Employees employee) {
        this.employee = employee;
    }

    public Date getEndDate() {
        return endDate;
    }

    public void setEndDate(Date endDate) {
        this.endDate = endDate;
    }

    public Date getStartDate() {
        return startDate;
    }

    public void setStartDate(Date startDate) {
        this.startDate = startDate;
    }
    
    
    public ReportsController() {
    
    }
    
    public Reports getSelected() {
        if (current == null) {
            current = new Reports();
            selectedItemIndex = -1;
        }
        return current;
    }
    
    private ReportsFacade getFacade() {
        return ejbFacade;
    }

    public PaginationHelper getPagination() {
        if (pagination == null) {
            pagination = new PaginationHelper(10) {

                @Override
                public int getItemsCount() {
                    return getFacade().count();
                }

                @Override
                public DataModel createPageDataModel() {
                    List<TimeLog> list=getFacade().getEmployeeReport(getEmployee(),getStartDate(),getEndDate());
                    return new ListDataModel(list);
                }
            };
        }
        return pagination;
    }
    
    public String prepareCreate() {
        current = new Reports();
        selectedItemIndex = -1;
        return "employeetimelist";
    }
    
    public String prepareProjectsCreate() {
        current = new Reports();
        selectedItemIndex = -1;
        return "projectsreport";
    }
    
    public String create() {
        try {
            getFacade().create(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("ReportsGenerated"));
            return prepareCreate();
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String update() {
        try {
            getFacade().edit(current);
            return "View";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String destroy() {
        TimeLog tl = (TimeLog) getItems().getRowData();
        System.out.println("##############Time Log ID: "+tl.getTlId());
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        try {
            getFacade().delete(tl);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("DeleteResult"));
        } catch (Exception e) {
            e.printStackTrace();
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
        recreateModel();
        return "reportsresult";
    }
    
    public String updateEmployeeTimeReport(){
        return getReports();
    }
    
    public String rejectProjectsReports(String tlId) {
        int tlID=Integer.parseInt(tlId);
        try {
            getFacade().updateTimeLog(tlID);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("RejectResult"));
        } catch (Exception e) {
            e.printStackTrace();
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
        recreateModel();
        return "projectreportsresult";
    }
    
    public String destroyProjectReport(String tlId){
        int tlID=Integer.parseInt(tlId);
        try {
            getFacade().deleteTL(tlID);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("DeleteResult"));
        } catch (Exception e) {
            e.printStackTrace();
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
        recreateModel();
        return "projectreportsresult";
    }
    
     public String destroyEmployeesReport(String tlId){
        int tlID=Integer.parseInt(tlId);
        try {
            getFacade().deleteTL(tlID);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("DeleteResult"));
        } catch (Exception e) {
            e.printStackTrace();
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
        recreateModel();
        return "reportsresult";
    }
     
     public String rejectEmployeesReport(String tlId){
        int tlID=Integer.parseInt(tlId);
        try {
            getFacade().updateTimeLog(tlID);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("RejectResult"));
        } catch (Exception e) {
            e.printStackTrace();
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
        recreateModel();
        return "reportsresult";
    }
    
    public String edit(){
        TimeLog tl = (TimeLog) getItems().getRowData();
        System.out.println("##############Time Log ID: "+tl.getTlId());
        System.out.println("##############Time Log Date: "+tl.getDate());
        System.out.println("##############Time Log Project: "+tl.getProject().getProjectName());
        System.out.println("##############Time Log Worked Hours: "+tl.getWorkedHours());
        return "/editemployeetimereport";
    }

    private void updateCurrentItem() {
        int count = getFacade().count();
        if (selectedItemIndex >= count) {
            // selected index cannot be bigger than number of items:
            selectedItemIndex = count - 1;
            // go to previous page if last page disappeared:
            if (pagination.getPageFirstItem() >= count) {
                pagination.previousPage();
            }
        }
        if (selectedItemIndex >= 0) {
            current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0);
        }
    }
    
    public DataModel getItems() {
        items=null;
        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        return items;
    }

    private void recreateModel() {
        items = null;
    }
    
    public String next() {
        getPagination().nextPage();
        recreateModel();
        return "List";
    }

    public String previous() {
        getPagination().previousPage();
        recreateModel();
        return "List";
    }
    
    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }
    
    @FacesConverter(forClass = Reports.class)
    public static class ReportsControllerConverter implements Converter {

        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            ReportsController controller = (ReportsController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "ReportsController");
            return controller.ejbFacade.find(getKey(value));
        }

        java.lang.Integer getKey(String value) {
            java.lang.Integer key;
            key = Integer.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Integer value) {
            StringBuffer sb = new StringBuffer();
            sb.append(value);
            return sb.toString();
        }

        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof Reports) {
                Reports o = (Reports) object;
                return getStringKey(o.getTlId());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + ReportsController.class.getName());
            }
        }
    }
    
    public String getReports(){
        return "reportsresult";
    }
    
    public String getProjectReport(){
        return "projectreportsresult";
        
    }
    
    
    public PaginationHelper getSearchPagination() {
        if (searchPagination == null) {
            searchPagination = new PaginationHelper(10) {
                @Override
                public int getItemsCount() {
                    return getFacade().count();
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(getFacade().getProjectReport(project,startDate,endDate));
                }
            };
        }
        return searchPagination;
    }

    public DataModel getSearchItems() {
        searchItems = null;
        if (searchItems == null) {
            searchItems = getSearchPagination().createPageDataModel();
            items = searchItems;
        }
        return items;
    }
}
